import { Global, Inject, Module } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import Redis from 'ioredis';

function getRedis() {
  const redis = new Redis({
    host: 'r-bp1nk4ntvylxc550xmpd.redis.rds.aliyuncs.com',
    port: 6379,
    username: 'r-bp1nk4ntvylxc550xm',
    password: 'Wuzhennan676', // 如果需要密码
  }); // 默认连接到 localhost:6379

  return new Promise((resolve, reject) => {
    redis.on('connect', () => {
      resolve(redis);
    });
    redis.on('error', (err) => {
      reject(err);
    });
  });
}

@Injectable()
export class RedisService {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
  constructor(@Inject('REDIS') public redis: Redis) {}
}

@Global()
@Module({
  providers: [
    RedisService,
    {
      provide: 'REDIS',
      useFactory: () => {
        return getRedis();
      },
    },
  ],
  exports: [RedisService],
})
export class RedisModule {}
